﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using KelonProud.Data;
using KelonProud.Infrastructure;
using Newtonsoft.Json;

namespace KelonProud.BackgroundJobs.Jobs.Base
{
   public abstract class DataJobBase: CronJobBase
    {
        #region 基础属性
        protected virtual string BaseUrl => "47.104.132.96";

        protected virtual string Account => "zhihuishulian";

        protected virtual string SecretKey => "ZHSL";
        
        protected abstract string RequestPath { get;  }
        #endregion

        #region 数据库属性
        protected abstract Dictionary<string,string> Fields { get; }

        protected abstract string TableName { get; }

        protected virtual string TempTableName => TableName + "_temp";
        #endregion



        public string GetRequestFullPath(DateTime beginTime, DateTime currentTime) {
            if (!RequestPath.HasValue()) {
                 throw new Exception("请求地址不能为空");
            }

            var beginTimeStamp = DateTimeToStamp(beginTime);
            var endTimeStamp = DateTimeToStamp(currentTime);

            return "http://{0}/{1}?account={2}&updateTime={3}&currentTime={4}&sign={5}"
                .FormatWith(BaseUrl, RequestPath,Account, beginTimeStamp, endTimeStamp, GetSign(beginTimeStamp, endTimeStamp));
        }

        private string GetSign(int beginTimeStamp, int endTimeStamp)
        {
            var key = "account={0}updateTime={1}currentTime={2}secretKey={3}"
                .FormatWith(Account, beginTimeStamp, endTimeStamp, SecretKey);

            return Utility.SHA1(key).ToLower();
        }

        /// <summary>
        /// Post 默认方式提供数据
        /// </summary>
        /// <param name="urlPath">WebApi请求地址</param>
        public static ResultData PostData(string urlPath)
        {
            var dataResult = new ResultData();
            try
            {
                using (var client = new HttpClient())
                {
                    var result = client.GetAsync(urlPath).Result;
                    var tokenResult = result.Content.ReadAsStringAsync().Result;
                    var tonkenResult = tokenResult.JsonToEntity<ApiResult>();

                    if (tonkenResult.Detail == "success")
                    {
                        dataResult = Aes.Aes.Decrypt(tonkenResult.Data).JsonToEntity<ResultData>();
                    }
                }
            }
            catch (Exception exception)
            {
                throw;
            }

            return dataResult;
        }

        private int DateTimeToStamp(System.DateTime time)
        {
            var startTime = TimeZoneInfo.Local.ToDateTime(new DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        protected List<dynamic> ResolveData(string json)
        {
           return json.JsonToList<dynamic>();
        }

        protected void ExecuteImportTemp(List<dynamic> dataList)
        {

        }

        protected void ExecuteTempToTable()
        {

        }

        protected virtual DateTime GetMaxDateTime()
        {
            using (var session= DatabaseSession.OpenSession())
            {
                var sql = "SELECT max(changeDate) from {0}".FormatWith(TableName);

                var result = session.ExecuteScalar<DateTime>(sql);

                return result;
            }
        }
    }
}
